<template>
  <div style="margin-top: 10px" v-loading="fullloading">
    <div style="margin-bottom: 10px;display: flex;justify-content: center;align-items: center">
      <el-input
        placeholder="默认展示全部用户，可以通过用户名搜索更多用户..."
        prefix-icon="el-icon-search"
        size="small"
        style="width: 400px;margin-right: 10px"
        v-model="keywords" clearable>
      </el-input>
      <el-button size="small" type="primary" icon="el-icon-search" @click="searchClick">搜索</el-button>
      <el-button size="small" type="primary" icon="el-icon-plus" @click="addClick">新增用户</el-button>
    </div>
    <div style="display: flex;justify-content: flex-start;flex-wrap: wrap;text-align: left">
      <el-card style="width: 350px;margin: 20px" v-for="(item,index) in hrs" :key="item.phone"  v-loading="cardLoading[index]">
        <div slot="header" class="clearfix">
          <span>{{item.name}}</span>
          <el-button type="text"
                     style="color: #f6061b;margin: 0px;float: right; padding: 3px 0;width: 15px;height:15px"
                     icon="el-icon-delete" @click="deleteHr(item.id)"></el-button>
        </div>
        <div>
          <div style="width: 100%;display: flex;justify-content: center">
            <img src='../../../static/images/touxiang.jpg' style="width: 70px;height: 70px;border-radius: 70px">
          </div>
          <div class="cardInfo">
            <div><span class="user-info">用户名:{{item.name}}</span></div>
            <div><span class="user-info">手机号码:{{item.phone}}</span></div>
            <div><span class="user-info">部门:{{item._department}}</span></div>
            <div class="user-info" style="display: flex;align-items: center;margin-bottom: 3px">
              用户状态:
              <el-switch
                style="display: inline;margin-left: 5px"
                v-model="item.enabled"
                active-color="#13ce66"
                inactive-color="#aaaaaa"
                active-text="启用"              
                @change="switchChange(item.enabled,item.id,index)"
                inactive-text="禁用">
              </el-switch>
            </div>
            <div class="user-info">
              用户角色:
              <el-tag
                v-for="role in item.roles"
                :key="role.nameZh"
                type="success"
                size="mini"
                style="margin-right: 5px"
                :disable-transitions="false">{{role.nameZh}}
              </el-tag>
              <el-popover
                v-loading="eploading[index]"
                placement="right"
                title="角色列表"
                width="200"
                @hide="updateHrRoles(item.id,index)"
                :key="item.id"
                trigger="click">
                <el-select v-model="selRoles" multiple placeholder="请选择角色">
                  <el-option
                    v-for="ar in allRoles"
                    :key="ar.id"
                    :label="ar.nameZh"
                    :value="ar.id">
                  </el-option>
                </el-select>
                <el-button type="text" icon="el-icon-more" style="color: #09c0f6;padding-top: 0px" slot="reference"
                           @click="loadSelRoles(item.roles,index)" :disabled="moreBtnState"></el-button>
            <!--<i class="el-icon-more" style="color: #09c0f6;cursor: pointer" slot="reference"
                   @click="loadSelRoles(item.roles,index)" disabled="true"></i>-->
              </el-popover>
            </div>
            <div><span class="user-info">备注:{{item.remark}}</span></div>
          </div>
        </div>
      </el-card>
    </div>
    <!-- 新增用户 -->
    <el-dialog title="新增用户" :visible.sync="dialogFormVisible" v-loading="dialogLoading"  width="40%">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="手机号" :label-width="formLabelWidth" prop='phone'>
          <el-input v-model="form.phone" autocomplete="off" clearable placeholder="请输入手机号"></el-input>
        </el-form-item>
        <!-- <el-form-item label="密码" :label-width="formLabelWidth"   prop='password'>
          <el-input v-model="form.password" autocomplete="off" clearable placeholder="请输入密码"></el-input>
        </el-form-item> -->
        <el-form-item label="姓名" :label-width="formLabelWidth"   prop='name'>
          <el-input v-model="form.name" autocomplete="off" clearable placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="部门" :label-width="formLabelWidth"   prop='department'>
           <el-select v-model="form.department" placeholder="请选择部门" style="width:100%;">
            <el-option
              v-for="item in form.departmentArray"
              :key="item.id"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.remark" autocomplete="off" clearable placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addSubmit('form')">确 定</el-button>
        <el-button @click="resetForm('form')">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      keywords: "",
      fullloading: false,
      hrs: [],
      cardLoading: [],
      eploading: [],
      allRoles: [],
      moreBtnState: false,
      selRoles: [],
      selRolesBak: [],
      dialogFormVisible: false,
      dialogLoading:false,
      form: {
          phone:'',
          name: '',
          department:"",
          departmentArray:[],
          remark:'',
      },
      rules: {
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '请输入手机号', trigger: 'blur' }
          ],
          department:[
            { required: true, message: '请选择部门', trigger: 'change' }
          ],
          // password: [
          //   { required: true, message: '请输入密码', trigger: 'blur' }
          // ],
      },
      formLabelWidth: '120px'
    };
  },
  mounted: function() {
    this.initCards();
    this.loadAllRoles();
    this.getRequest("/common/getDepartmentInfo").then(resp =>{
      if(resp && resp.status==200){ 
          this.form.departmentArray=resp.data.obj.departmentList;
      }
    })
    console.log(this.$store.state)
  },
  methods: {
    searchClick() {
      this.initCards();
      this.loadAllRoles();
    },
    addClick(){
      this.dialogFormVisible=true;
    },
    resetForm(formName) {
      this.dialogFormVisible=false;
      this.$refs[formName].resetFields();
      this.form.remark=''
    },
    // 提交添加人员
    addSubmit(form){
      this.$refs[form].validate((valid) => {
          if (valid) {
            var that=this;
            this.dialogLoading=true;
            this.putRequest("/system/user/user/insert", {
              phone: that.form.phone,
              name: that.form.name,
              _department:that.form.department,
              remark: that.form.remark,
            }).then(resp => {
              that.dialogLoading=false;
              if(resp && resp.data.status==200){
                that.dialogFormVisible=false;
                that.form.remark='';
                that.$refs[form].resetFields();
                that.initCards();
                that.loadAllRoles();
                that.common.showToast('success',resp.data.msg)
              }
            });
          } else {
            return false;
          }
      });
    },
    updateHrRoles(hrId, index) {
      this.moreBtnState = false;
      var _this = this;
      if (this.selRolesBak.length == this.selRoles.length) {
        for (var i = 0; i < this.selRoles.length; i++) {
          for (var j = 0; j < this.selRolesBak.length; j++) {
            if (this.selRoles[i] == this.selRolesBak[j]) {
              this.selRolesBak.splice(j, 1);
              break;
            }
          }
        }
        if (this.selRolesBak.length == 0) {
          return;
        }
      }
      this.eploading.splice(index, 1, true);
      this.putRequest("/system/user/roles", {
        userId: hrId,
        rids: this.selRoles
      }).then(resp => {
        _this.eploading.splice(index, 1, false);
        if (resp && resp.status == 200) {
          var data = resp.data;
          // _this.refreshHr(hrId, index);
          _this.initCards();
          _this.loadAllRoles();
          _this.common.showToast('success',resp.data.msg)
        }
      });
    },
    refreshHr(hrId, index) {
      var _this = this;
      _this.cardLoading.splice(index, 1, true);
      this.putRequest("/common/user/id/" + hrId).then(resp => {
        _this.cardLoading.splice(index, 1, false);
        _this.hrs.splice(index, 1, resp.data);
      });
    },
    loadSelRoles(hrRoles, index) {
      this.moreBtnState = true;
      this.selRoles = [];
      this.selRolesBak = [];
      hrRoles.forEach(role => {
        this.selRoles.push(role.id);
        this.selRolesBak.push(role.id);
      });
    },
    loadAllRoles() {
      var _this = this;
      this.getRequest("/system/basic/roles").then(resp => {
        _this.fullloading = false;
        if (resp && resp.status == 200) {
          _this.allRoles = resp.data;
        }
      });
    },
    switchChange(newValue, hrId, index) {
      var _this = this;
      _this.cardLoading.splice(index, 1, true);
      this.putRequest("/system/user/", {
        enabled: newValue,
        id: hrId
      }).then(resp => {
        _this.cardLoading.splice(index, 1, false);
        if (resp && resp.status == 200) {
          _this.common.showToast('success',resp.data.msg)
          var data = resp.data;
          if (data.status == "error") {
            _this.refreshHr(hrId, index);
          }
        } else {
          _this.refreshHr(hrId, index);
        }
      });
    },
    initCards() {
      this.fullloading = true;
      var _this = this;
      var searchWords;
      if (this.keywords === "") {
        searchWords = "all";
      } else {
        searchWords = this.keywords;
      }
      this.getRequest("/system/user/" + searchWords).then(resp => {
        if (resp && resp.status == 200) {
          _this.hrs = resp.data;
          var length = resp.data.length;
          _this.cardLoading = Array.apply(null, Array(length)).map(function(
            item,
            i
          ) {
            return false;
          });
          _this.eploading = Array.apply(null, Array(length)).map(function(
            item,
            i
          ) {
            return false;
          });
        }
      });
    },
    // 删除人员
    deleteHr(hrId) {
      this.$confirm("将删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          var _this = this;
          this.fullloading = true;
          this.deleteRequest("/system/user/" + hrId).then(resp => {
            _this.fullloading = false;
            if (resp && resp.data.status == 200) {
              var data = resp.data;
              _this.common.showToast('success',resp.data.msg)
              _this.initCards();
              _this.loadAllRoles();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>
<style scoped>
.el-card{
  width: 28% !important;
  margin:1% !important;
}
.user-info {
  font-size: 12px;
  color: #09c0f6;
}
.cardInfo{
  margin-top: 20px;
}
.cardInfo div{
  line-height: 25px;
}
</style>
